package juc.utils.exchanger;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 有且只有两个线程间交换数据，双向
 */
public class ExchangeExample1 {
    /**
     * V r = exchange(V v)
     * &nbsp;&nbsp;v: indicate the object the current thread wanted transfer.
     * &nbsp;&nbsp;r: indicate the other thread(pair) return object.
     * <p/>
     * <pre>
     *     NOTE:
     *      1. if the pair thread not reached exchange point,the thread will WAITING.
     *      2. use the (@link Exchanger) must be paired.
     * </pre>
     * @param args
     */
    public static void main(String[] args) {
        final Exchanger<String> exchanger = new Exchanger<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " start.");
                try {
                    String result = exchanger.exchange("I am come from T-A",4,TimeUnit.SECONDS);
                    System.out.println(Thread.currentThread().getName() + " get value [" + result + "]");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                    System.out.println("time out.");
                }
                System.out.println(Thread.currentThread().getName() + " end.");

            }
        }, "==A==").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " start.");
                try {
                    TimeUnit.SECONDS.sleep(6);
                    String result = exchanger.exchange("I am come from T-B");
                    System.out.println(Thread.currentThread().getName() + " get value [" + result + "]");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " end.");

            }
        }, "==B==").start();
    }
}
